package com.example.haiti.infrastructure.surveyor;

import java.io.File;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class exterior_Activity extends Activity {
	
    private Utils utilsHelper = null;
    private Cursor structureCursor = null;
    private int structureID;
    private Context mContext =  null;
    private static int CAPTURE_IMAGE = -1;
    
    private static final int CAPTURE_IMAGE_FRONT = 0;
    private static final int CAPTURE_IMAGE_RIGHT = 1;
    private static final int CAPTURE_IMAGE_BACK = 2;
    private static final int CAPTURE_IMAGE_LEFT = 3;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.exterior_layout);
        mContext = this;        
        utilsHelper = new Utils(exterior_Activity.this);      
        utilsHelper.openDatabase(); 

        // Initializes view
    	getStructure();       	       
        setupPhotoButtons();
        setupNextButton();
                 
    } // end of the onCreate method
    
    @Override
    protected void onPause() {
        super.onPause();

        utilsHelper.closeDatabase();
    }
    
    @Override
    protected void onStop() {
      super.onStop();
       
    	utilsHelper.closeDatabase();
    }
    
    private void getStructure(){
    	// Get structure ID
        structureID = getIntent().getIntExtra("structureID", 1000); //Get structureID otherwise 1000      
        structureCursor = utilsHelper.getStructureCursor(structureID);	    	
    }

    
    private void setupPhotoButtons(){
    	
    	
    	// Front Photo Button =================================================================================
    	ImageButton btnFront = (ImageButton) findViewById(R.id.btnExteriorFront);
    	
        if (photoAlreadyTaken(CAPTURE_IMAGE_FRONT)){
	        btnFront.setImageResource(R.drawable.check);
        } 
    	
        btnFront.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
               	takePhoto(CAPTURE_IMAGE_FRONT);
           
            }
        }); // End of  Next button click listener   
    	
    	// Right Photo Button =================================================================================
        ImageButton btnRight = (ImageButton) findViewById(R.id.btnExteriorRight);
        
        if (photoAlreadyTaken(CAPTURE_IMAGE_RIGHT)){
	        btnRight.setImageResource(R.drawable.check);
        } 
        
        btnRight.setOnClickListener(new OnClickListener() {

        	public void onClick(View v) {
               	takePhoto(CAPTURE_IMAGE_RIGHT);
                   	
           
            }
        }); // End of  Next button click listener   
        
    	//  Back Photo Button =================================================================================
        ImageButton btnBack = (ImageButton) findViewById(R.id.btnExteriorBack);
        
        if (photoAlreadyTaken(CAPTURE_IMAGE_BACK)){
	        btnBack.setImageResource(R.drawable.check);
        } 
        
        btnBack.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                   	takePhoto(CAPTURE_IMAGE_BACK);
          
            }
        }); // End of  Next button click listener   
        
    	// Left Photo Button =================================================================================
        ImageButton btnLeft = (ImageButton) findViewById(R.id.btnExteriorLeft);
        
        if (photoAlreadyTaken(CAPTURE_IMAGE_LEFT)){
		        btnLeft.setImageResource(R.drawable.check);
        } 

        btnLeft.setOnClickListener(new OnClickListener() {
        	
            public void onClick(View v) {
               	takePhoto(CAPTURE_IMAGE_LEFT);           	
           
            }        
        }); // End of  Next button click listener    	  	
    }  
    
    private boolean photoAlreadyTaken(int photoSide){
    	
    	boolean exists = false;
    	String photo_value =  null;
    	
    	switch (photoSide){
    	
    		case CAPTURE_IMAGE_FRONT:
    	        photo_value = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_PHOTO_FRONT));
    			break;
    			
    		case CAPTURE_IMAGE_RIGHT:
    	        photo_value = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_PHOTO_RIGHT));
    			break;
    			
    		case CAPTURE_IMAGE_BACK:
    	        photo_value = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_PHOTO_BACK));
    			break;
    			
    		case CAPTURE_IMAGE_LEFT:
    	        photo_value = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_PHOTO_LEFT));
    			break;
    			
            default:
            	Log.d(LAYOUT_INFLATER_SERVICE, "IMAGE EXISTS ERROR");
            	break;	
    			    	
    	}
    	
    	if (photo_value != null){
    		exists = true;
    	}

    	return  exists;
    }
    
    private void takePhoto(int photoSide){
    	
    	// Determines which photo
    	CAPTURE_IMAGE = photoSide;
    	
    	String photoPath = getPhotoPath(photoSide); 
    	        
        File outFile = new File(photoPath); 	
    	Uri iImageOutputUri = Uri.fromFile( outFile );

    	// Start camera intent to capture image and store the file locally
    	// REQ: 3.4.4.R3 met
    	Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
    	intent.putExtra( MediaStore.EXTRA_OUTPUT, iImageOutputUri );

        utilsHelper.closeDatabase();
    	((Activity)mContext).startActivityForResult(intent, CAPTURE_IMAGE);  	
    	}
    
    private String getPhotoPath(int photoSide){
    	    	
    	
		File file = Environment.getExternalStorageDirectory();
	    String structureName = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_NAME));	 			
        String photo_directory = file.getAbsolutePath() + "/Haiti_Structure_Photos/" + structureName ;
        
        // Creates new directory if needed
    	File dir = new File(photo_directory);
        if (!dir.isDirectory())
            dir.mkdirs();
        
        String photoSideText = "";
    	
    	switch (photoSide){
    		
    		case CAPTURE_IMAGE_FRONT:
    			photoSideText = "Front";
    			break;
    		case CAPTURE_IMAGE_RIGHT:
    			photoSideText = "RIGHT";
    			break;
    			
    		case CAPTURE_IMAGE_BACK:
    			photoSideText = "Back";
    			break;
    			
    		case CAPTURE_IMAGE_LEFT:
    			photoSideText = "Left";
    			break;
    			
            default:
            	Log.d(LAYOUT_INFLATER_SERVICE, "Wrong Image");
            	break;		 		    		
    	}
    	
    	String photoPath = photo_directory + File.separator + structureName + "_" + photoSideText + ".jpg";
		
    	return photoPath;  		
    }
    
    
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  

	 	if (resultCode == RESULT_OK) {
	 		
	        utilsHelper.openDatabase();
	 		
	 		if (requestCode == CAPTURE_IMAGE_FRONT){
	 	        String photoPath = getPhotoPath(CAPTURE_IMAGE_FRONT);
	 	        File photo = new File(photoPath);
	 	        	 			 
	 			if (photo.exists()){
	 		        
	                String[][] databaseUpdates = {
	                    {SqlHelper.COLUMN_STRUCTURE_PHOTO_FRONT, photoPath},
	                    };
	                utilsHelper.dbHelper.updateStructureEntry(databaseUpdates, structureID ); 
	 				
	 				ImageButton btnFront = (ImageButton) findViewById(R.id.btnExteriorFront);
	 		        btnFront.setImageResource(R.drawable.check);
		 			Toast.makeText(mContext,"Photo saved",Toast.LENGTH_SHORT).show(); 	 			
		 		}

	 		}
	 		if (requestCode == CAPTURE_IMAGE_RIGHT){
	 	        String photoPath = getPhotoPath(CAPTURE_IMAGE_RIGHT);
	 	        File photo = new File(photoPath);
	 	        	 			 
	 			if (photo.exists()){
	 				
	                String[][] databaseUpdates = {
                        {SqlHelper.COLUMN_STRUCTURE_PHOTO_RIGHT, photoPath},
                        };
	                
	                utilsHelper.dbHelper.updateStructureEntry(databaseUpdates, structureID ); 
	 						
	 		        ImageButton btnRight = (ImageButton) findViewById(R.id.btnExteriorRight);
	 		        btnRight.setImageResource(R.drawable.check);
		 			Toast.makeText(mContext,"Photo saved",Toast.LENGTH_SHORT).show(); 	 			
		 		}

	 		}
	 		if (requestCode == CAPTURE_IMAGE_BACK){
	 	        String photoPath = getPhotoPath(CAPTURE_IMAGE_BACK);
	 	        File photo = new File(photoPath);
	 	        	 			 
	 			if (photo.exists()){
	 				
	                String[][] databaseUpdates = {
                        {SqlHelper.COLUMN_STRUCTURE_PHOTO_BACK, photoPath},
                        };
                
	                utilsHelper.dbHelper.updateStructureEntry(databaseUpdates, structureID ); 
	 				
	 		        ImageButton btnBack = (ImageButton) findViewById(R.id.btnExteriorBack);
	 		        btnBack.setImageResource(R.drawable.check);
		 			Toast.makeText(mContext,"Photo saved",Toast.LENGTH_SHORT).show(); 	 			
		 		}
	 		}
	 		if (requestCode == CAPTURE_IMAGE_LEFT){
	 	        String photoPath = getPhotoPath(CAPTURE_IMAGE_LEFT);
	 	        File photo = new File(photoPath);
	 	        	 			 
	 			if (photo.exists()){
	 				
	                String[][] databaseUpdates = {
                        {SqlHelper.COLUMN_STRUCTURE_PHOTO_LEFT, photoPath},
                        };
	                
	                utilsHelper.dbHelper.updateStructureEntry(databaseUpdates, structureID ); 
	 				
	 		        ImageButton btnLeft = (ImageButton) findViewById(R.id.btnExteriorLeft);
	 		        btnLeft.setImageResource(R.drawable.check);	 			 				
		 			Toast.makeText(mContext,"Photo saved",Toast.LENGTH_SHORT).show(); 	 			
		 		}
	 		}
	    } // IF  RESULT ==  OK
  	
    } // On Activity Result
	
	  
    private void setupNextButton(){
    	 	
    	// Add Next button
        Button btnNextQuestions = (Button) findViewById(R.id.buttonNext);
        btnNextQuestions.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                   	
                utilsHelper.startNextActivity(structureID, main_Activity.class);             
            }
        }); // End of  Next button click listener            
    }       
    
    // Back Button Pressed
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if ((keyCode == KeyEvent.KEYCODE_BACK))
        {
            utilsHelper.startNextActivity(structureID, questionnaire_Activity3.class);
        }
        return super.onKeyDown(keyCode, event);
    }
} 